<script setup>
  import { ref, watch, onMounted } from 'vue'
  import { ElMessage } from 'element-plus';
  import { queryClazzApi, addClazzApi, queryClazzByIdApi, updateClazzApi, deleteClazzByIdApi } from '@/api/clazz'
  import { queryEmpList } from '../../api/emp';
  import { ElMessageBox } from 'element-plus';
  const searchClazz = ref({
    name: '',
    begin: '',
    end: '',
    date: []
  })

  const clazzList = ref([])
  const search = async () => {
    const res = await queryClazzApi(searchClazz.value.name,
                              searchClazz.value.begin,
                              searchClazz.value.end,
                              currentPage.value,
                              pageSize.value)
    if (res.code){
      clazzList.value = res.data.rows
      total.value = res.data.total
    }
  }

  const clear = () => {
    searchClazz.value = {
      name: '',
      gender: '',
      date: [],
      begin: '',
      end: '',
    }
    search()
  }

  onMounted(() => {
    search()
    queryEmp()
  })

  watch(() => searchClazz.value.date, (newVal,oldVal) => {
    if (newVal && newVal.length > 0){
      searchClazz.value.begin = newVal[0]
      searchClazz.value.end = newVal[1]
    }else{
      searchClazz.value.begin = ''
      searchClazz.value.end = ''
    }
  }
  )

  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const handleSizeChange = (val) => {
    search()
  }
  const handleCurrentChange = (val) => {
    search()
  }

  const add = () => {
    clazzForm.value = {
      name:'',
      room:'',
      beginDate:'',
      endDate:'',
      masterId:'',
      subject:''
    }
    showDialog.value = true
    formTitle.value = '新增班级'
    if (clazzFormRef.value){
      clazzFormRef.value.resetFields()
    }
  }

  const showDialog = ref(false)
  const formTitle = ref('')

  const clazzForm = ref({
    name:'',
    room:'',
    beginDate:'',
    endDate:'',
    masterId:'',
    subject:''
  })

  const emps = ref([]);

  const subjects = ref([{ name: 'java', value: 1 },{ name: '前端', value: 2 },{ name: '大数据', value: 3 },{ name: 'Python', value: 4 },{ name: 'Go', value: 5 },{ name: '嵌入式', value: 6 }])
  const queryEmp = async () => {
    const res = await queryEmpList()
    if (res.code){
      emps.value = res.data
    }
  }

  const save = async () => {
    if (!clazzFormRef) return
    await clazzFormRef.value.validate (async(valid,fields)=>{
    if (valid){
      let res
      if (clazzForm.value.id){
        res = await updateClazzApi(clazzForm.value)
      }else{
        res = await addClazzApi(clazzForm.value)
      }
      if (res.code){
        ElMessage.success('保存成功')
        showDialog.value = false
        search()
      }else{
        ElMessage.error('保存失败')
      }
    }else{
      ElMessage.error('校验失败')
    }
    })
  }

  const rules = ref({
    name: [
      { required: true, message: '班级名称为必填项', trigger: 'blur' },
      { min: 4, max: 30, message: '班级名长度为4-30个字', trigger: 'blur' }
    ],
    beginDate: [
      { required: true, message: '开课时间为必填项', trigger: 'blur' },
    ],
    endDate: [
      { required: true, message: '开课时间为必填项', trigger: 'blur' }
    ],
    subject: [
      { required: true, message: '学科为必填项', trigger: 'blur' },
    ]
  })

  const clazzFormRef = ref() 

  const edit = async (id) => {
    showDialog.value = true
    formTitle.value = '修改班级'
    const res = await queryClazzByIdApi(id)
    clazzForm.value = res.data
  }

  const del = (id) => {
    ElMessageBox.confirm(
    '确定要删除此数据吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
    ).then(async () => {
      const res = await deleteClazzByIdApi(id)
      if (res.code){
        ElMessage.success('删除成功')
        search()
      }else{
        ElMessage.error(res.msg)
      }
    }).catch(() => {
      ElMessage.info('取消操作')
    })
  }

</script>
  
<template>
  <h1>班级管理</h1>
  <!-- 表单 -->
  <el-form :inline="true" :model="searchClazz" class="clazz-search" >
    <el-form-item label="班级名称">
      <el-input v-model="searchClazz.name" placeholder="请输入班级名称" clearable />
    </el-form-item>
    <el-form-item label="结课时间">
      <div class="block">
      <el-date-picker
        v-model="searchClazz.date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
      />
    </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 增加操作按钮 -->
  <div class="button-group">
    <el-button type="primary" @click="add">+ 新增班级</el-button>
  </div>

  <!-- 表格 -->
  <el-table :data="clazzList" border style="width: 100%;">
    <el-table-column type="index"  label="序号" width="80" align="center"/>
    <el-table-column prop="name" label="班级名称" width="200" align="center"/>
    <el-table-column prop="room" label="班级教室" width="100" align="center"/>
    <el-table-column prop="masterName" label="班主任" width="100" align="center"/>
    <el-table-column prop="beginDate" label="开课时间" width="150" align="center"/>
    <el-table-column prop="endDate" label="结课时间" width="150" align="center"/>
    <el-table-column prop="status" label="状态" width="100" align="center"/>
    <el-table-column prop="updateTime" label="最后修改时间" width="200" align="center"/>
    <el-table-column fixed="right" label="操作" align="center">
      <template #default="scope">
        <el-button size="small" @click="edit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

    <!-- 分页条 -->
  <div class="pagination-block">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 增改班级表单 -->
  <el-dialog v-model="showDialog" :title="formTitle" width="30%">
    <el-form :model="clazzForm" :rules="rules" ref="clazzFormRef">
      <el-form-item label="班级名称" prop="name" label-width="80px">
        <el-input v-model="clazzForm.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="班级教室" label-width="80px">
        <el-input v-model="clazzForm.room" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="开课时间" prop="beginDate" label-width="80px">
        <el-date-picker v-model="clazzForm.beginDate" type="date" style="width: 100%;" placeholder="请选择开课时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <el-form-item label="结课时间" prop="endDate" label-width="80px">
        <el-date-picker v-model="clazzForm.endDate" type="date" style="width: 100%;" placeholder="请选择结课时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <el-form-item label="班主任" label-width="80px">
        <el-select v-model="clazzForm.masterId" placeholder="请选择部门" style="width: 100%;">
          <el-option v-for="emp in emps" :label="emp.name" :value="emp.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学科" prop="subject" label-width="80px">
        <el-select v-model="clazzForm.subject" placeholder="请选择学科" style="width: 100%;">
          <el-option v-for="sub in subjects" :label="sub.name" :value="sub.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
  .clazz-search {
    margin: 20px 0;
  }
  .button-group {
    margin-bottom: 10px;
  }
  .pagination-block {
    margin: 20px 0;
  }
  .avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border-radius: 10px;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>